<template>
  <div class="students_box">
    <div class="header">
      <div class="search">
        <el-input v-model="search" size="small" placeholder="请输入学号" />
        <el-button type="primary" :icon="Search" @click="mySearch" />
        <el-button type="primary" :icon="Plus" @click="addStudent">添加</el-button>
        <el-button type="primary" @click="emptySearchData" v-show="searchDataLength">返回</el-button>
      </div>
      <div class="count">
        共有数据:&nbsp;{{ tableData.length }}&nbsp;条
      </div>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="searchDataLength ? searchData : filterTableData" 
      border 
      style="width: 100%"
    >
      <el-table-column
        v-for="(item, index) in studentInfo"
        :key="index"
        :label="student[item]"
        :prop="item"
        align="center"
      />
      <el-table-column align="center">
        <template #header>操作</template>
        <template #default="scope">
          <!-- 编辑 -->
          <el-button 
            type="primary" 
            size="small" 
            :icon="Edit" 
            @click="handleEdit(scope.$index, scope.row)"
          />
          <!-- 删除 -->
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      small
      background
      layout="prev, pager, next, jumper"
      :total="tableData.length"
      :page-size="pageSize"
      @current-change="currentChange"
      v-show="!searchDataLength"
    />
  </div>
  <AddStudent 
    v-if="inShow" 
    @myShow="myShow" 
    :student="studentObj" 
    @childAddStudent="childAddStudent"
    @childUpdateStudent="childUpdateStudent"
  />
</template>

<script setup>
import { ref, computed, onMounted } from "vue"
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search, Edit, Delete, Plus } from "@element-plus/icons-vue"
import { getStudents, addStudent as myAddStudent, updateStudent, deleteStudent } from '@/http/students'
import AddStudent from './AddStudent.vue'

// 搜素的 value 值
const search = ref("")
// 每页显示条目个数
const pageSize = ref(10)
// 当前页数
const currentPage = ref(1)
// 学生信息对象
const student = {
  sno: "学号",
  name: "姓名",
  sex: "性别",
  age: "年龄",
  telephone: "联系方式",
  major: "专业",
  bj: "班级",
  dorm: "寝室",
}
const studentInfo = [
  "sno",
  "name",
  "sex",
  "age",
  "telephone",
  "major",
  "bj",
  "dorm",
]
// 学生数据
const tableData = ref([])
// 搜索出来的数据
const searchData = ref([])
// 显示影藏添加
const inShow = ref(false)
// 传递给子组件的学生信息对象
const studentObj = ref({})

// 异步请求获取学生数据
const getStudentData = async () => {
  const data = await getStudents()
  tableData.value = data
}
onMounted(getStudentData)

// 筛选要展示的数据
const filterTableData = computed(
  () => {
    // 开始截取的索引
    const startIndex = (currentPage.value - 1) * pageSize.value;
    // 结束截止的索引
    const endIndex = currentPage.value * pageSize.value;
    return tableData.value.slice(startIndex, endIndex);
  }
)
// 获取搜索的数据个数
const searchDataLength = computed(() => searchData.value.length)
// 搜索
const mySearch = () => {
  // 判断输入是否为空
  if(search.value === '') return ElMessage.error('请输入学号!')
  // 查询满足条件的
  searchData.value = tableData.value.filter( item => item.sno === search.value)
  if(searchData.value.length === 0) return ElMessage.warning('查无结果，请确认输入是否正确!')
}
// 清空搜索的数据
const emptySearchData = () => {
  searchData.value = []
}
// 添加
const addStudent = () => {
  inShow.value = true
}
// 子传父事件(隐藏弹出框)
const myShow = (bool) => {
  inShow.value = bool
  studentObj.value = {}
}
// 子传父事件(添加学生)
const childAddStudent = async (data) => {
  const { msg } = await myAddStudent(data)
  // 重新获取数据
  getStudentData()
  ElMessage.success(msg)
}
// 子传父事件(更新学生)
const childUpdateStudent = async (data) => {
  const { msg } = await updateStudent(data)
  // 重新获取数据
  getStudentData()
  ElMessage.success(msg)
}
// 编辑
const handleEdit = (index, row) => {
  studentObj.value = row
  inShow.value = true
}
// 删除
const handleDelete = (index, row) => {
  // 确认提示框
  ElMessageBox.confirm(
    `确定删除学生"${row.name}"吗?`,
    '友情提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then( async () => {
    const { msg } = await deleteStudent({ id: row.id })
    ElMessage.success(msg)
    // 删除后重新获取数据
    getStudentData()
  })
  .catch(() => {})
}

// currentChange 页数改变时触发
const currentChange = (val) => {
  currentPage.value = val;
}

</script>
<style scoped lang='scss'>
:deep(.el-input__inner) {
  margin-right: 10px;
  width: 150px;
  height: 35px;
}
:deep(.el-table th.el-table__cell) {
  background-color:#f5f5f5;
}
:deep(.el-pagination) {
  margin-top: 15px;
  justify-content: center;
}

.students_box {
  padding: 0 15px;
}
.header {
  display: flex;
  padding-right: 20px;
  height: 60px;
  align-items: center;
  justify-content: space-between;
  .search {
    display: flex;
    align-items: center;
  }
  .count {
    font-size: 14px;
    color: #333;
  }
}
</style>